package com.wy.tranFile.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class DecryptionUtil {
    // 固定密钥字符串
    private static final String secretKeyString = "mysecretkey12345"; // 应该是16、24或32字符长
    private static final byte[] keyBytes = secretKeyString.getBytes(StandardCharsets.UTF_8);

    /**
     * 进行加密
     *
     * @param uuid
     * @return
     */
    public static String encrypt(String uuid) throws Exception {
        return Base64.getUrlEncoder().encodeToString(encrypt(uuid, keyBytes));
    }


    /**
     * 进行解密
     *
     * @param encryptedUuid
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedUuid) throws Exception {
        String uuid = new String(decrypt(encryptedUuid, keyBytes));
        return uuid;
    }

    public static byte[] encrypt(String str, byte[] keyBytes) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        return cipher.doFinal(str.getBytes());
    }

    public static byte[] decrypt(String str, byte[] keyBytes) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return cipher.doFinal(Base64.getUrlDecoder().decode(str));
    }
}
